package com.lanhai.zhonglai.utils;

import com.lanhai.zhonglai.enums.DotTypeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Objects;
import java.util.Set;

@Component
public class DmdUtils {
    @Autowired
    private JedisPool jedisPool;

    //给待命点加个锁
    public void lockDmd(String agvid, String dotid) {

        Jedis resource = jedisPool.getResource();

        Set<String> keys = resource.keys("lockDmd_dot:*");
        //检查是否小车已经跟待命点有关联
        boolean flag = keys.stream().anyMatch(item -> Objects.equals(resource.get(item), agvid));
        if (!flag) {
            resource.set("lockDmd_agv:" + agvid, dotid);
            resource.set("lockDmd_dot:" + dotid, agvid);

            //清除多余的缓存
            keys.forEach(item -> {
                if (Objects.equals(resource.get(item), agvid) && !item.contains(dotid)) {
                    resource.del(item);
                }
            });
        }
        resource.close();
    }

    //待命点清理缓存
    public void clearlockDmd(String agvid, String dotid) {
        Jedis resource = jedisPool.getResource();
        resource.del("lockDmd_agv:" + agvid, dotid);
        resource.del("lockDmd_dot:" + dotid, agvid);

        //清除多余的缓存
        Set<String> keys = resource.keys("lockDmd_dot:*");
        keys.forEach(item -> {
            if (Objects.equals(resource.get(item), agvid)) {
                resource.del(item);
            }
        });

        resource.close();
    }


    //获取制绒空闲的待命点
    public String checkDmdbyZrs(Integer agvid) {
        String[] zrdmdcode = {"643", "644", "645"};
        Jedis resource = jedisPool.getResource();

        try {
            for (String code : zrdmdcode) {
                if (!resource.exists("lockDmd_dot:" + code)) {
                    return code;
                } else {
                    String s = resource.get("lockDmd_dot:" + code);
                    if (Objects.equals(s, agvid)) {
                        return code;
                    }
                }
            }
        }finally {
            resource.close();
        }
        return null;
    }


    public void clearDmdChech(String agvid) {
        Jedis resource = jedisPool.getResource();
        //清除除开到达待命点以外的待命点缓存

        if (resource.exists("lockDmd_agv:" + agvid)) {
            resource.del("lockDmd_dot:" + resource.get("lockDmd_agv:" + agvid));
            resource.del("lockDmd_agv:" + agvid);
        }
        resource.close();
    }


}
